<script setup lang="ts">
import type { UploadFile, UploadInstance, UploadRequestOptions } from "element-plus"
import type { CreateOrUpdateCompanyRequest } from "@/pages/internship/company/apis/type"
import { DocumentChecked, InfoFilled, OfficeBuilding, PhoneFilled, Plus } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { computed, nextTick, reactive, ref, watch } from "vue"
import { useCompanyStore } from "@/pinia/stores/company"

const props = defineProps<{
  modelValue: boolean
  companyId?: number
  editMode?: boolean // true表示编辑模式，false表示新增模式
}>()

const emit = defineEmits<{
  "update:modelValue": [value: boolean]
  "close": []
  "success": []
}>()

const companyStore = useCompanyStore()

// 表单数据
const formData = reactive<CreateOrUpdateCompanyRequest>({
  companyId: 0,
  companyName: "",
  shortName: "",
  workCity: undefined,
  companyType: undefined,
  companyScale: undefined,
  contactPerson: "",
  contactPhone: "",
  contactEmail: "",
  address: "",
  introduction: "",
  licenseNo: "",
  licenseUrl: "",
  expirationTime: "",
  status: 1,
  tags: []
})

// 表单验证规则
const rules = reactive({
  companyName: [
    { required: true, message: "请输入公司名称", trigger: "blur" },
    { min: 2, max: 100, message: "公司名称长度应为2-100个字符", trigger: "blur" }
  ],
  shortName: [
    { required: true, message: "请输入公司简称", trigger: "blur" },
    { max: 50, message: "公司简称长度不能超过50个字符", trigger: "blur" }
  ],
  workCity: [
    { required: true, message: "请选择工作城市", trigger: "change" }
  ],
  companyType: [
    { required: true, message: "请选择公司类型", trigger: "change" }
  ],
  companyScale: [
    { required: true, message: "请选择公司规模", trigger: "change" }
  ],
  contactPerson: [
    { required: true, message: "请输入联系人", trigger: "blur" },
    { min: 1, max: 20, message: "联系人长度应为1-20个字符", trigger: "blur" }
  ],
  contactPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号码", trigger: "blur" }
  ],
  contactEmail: [
    { required: false, message: "请输入联系邮箱", trigger: "blur" },
    { type: "email" as const, message: "请输入有效的邮箱地址", trigger: "blur" }
  ],
  address: [
    { required: true, message: "请输入公司地址", trigger: "blur" },
    { min: 5, max: 200, message: "公司地址长度应为5-200个字符", trigger: "blur" }
  ],
  introduction: [
    { max: 500, message: "公司介绍长度不能超过500个字符", trigger: "blur" }
  ],
  licenseNo: [
    { required: true, message: "请输入营业执照号码", trigger: "blur" },
    { min: 1, max: 50, message: "营业执照号码长度应为1-50个字符", trigger: "blur" }
  ],
  expirationTime: [
    { required: true, message: "请选择营业执照到期时间", trigger: "change" }
  ]
})

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: value => emit("update:modelValue", value)
})
const formRef = ref()
const uploadRef = ref<UploadInstance>()
const fileList = ref<UploadFile[]>([])
const loading = ref(false)
const submitLoading = computed(() => companyStore.submitLoading)

// 从store获取选项数据
const workCityOptions = computed(() => companyStore.options.workCityOptions)
const companyTypeOptions = computed(() => companyStore.options.companyTypeOptions)
const companyScaleOptions = computed(() => companyStore.options.companyScaleOptions)

watch([() => props.companyId, () => props.editMode, () => props.modelValue], ([newCompanyId, newEditMode, newVisible]) => {
  if (newVisible) {
    if (newEditMode && newCompanyId && newCompanyId > 0) {
      loadCompanyData(newCompanyId)
    } else if (newEditMode) {
      console.log("编辑模式但没有有效的公司ID")
      ElMessage.warning("无法加载公司数据：无效的公司ID")
    } else {
      console.log("新增模式")
      resetForm()
    }
  }
}, { immediate: true })

async function loadCompanyData(companyId: number) {
  console.log("开始加载公司数据，ID:", companyId)
  loading.value = true
  try {
    // 先重置表单，避免旧数据残留
    resetForm()

    let detailData = null
    if (props.editMode) {
      detailData = await companyStore.fetchCompanyForUpdate(companyId)
      console.log("获取到的公司更新数据:", detailData)
    } else {
      detailData = await companyStore.fetchCompanyDetail(companyId)
      console.log("获取到的公司详情:", detailData)
    }

    if (detailData) {
      // 确保表单引用已经初始化
      await nextTick()

      // 填充表单数据
      Object.assign(formData, {
        companyId: detailData.companyId || 0,
        companyName: detailData.companyName || "",
        shortName: detailData.shortName || "",
        workCity: detailData.workCity || undefined,
        companyType: detailData.companyType || undefined,
        companyScale: detailData.companyScale || undefined,
        contactPerson: detailData.contactPerson || "",
        contactPhone: detailData.contactPhone || "",
        contactEmail: detailData.contactEmail || "",
        address: detailData.address || "",
        introduction: detailData.introduction || "",
        licenseNo: detailData.licenseNo || "",
        licenseUrl: detailData.licenseUrl || "",
        expirationTime: detailData.expirationTime || "",
        status: detailData.status,
        tags: detailData.tags || []
      })

      // 如果有执照URL，更新文件列表以显示图片
      if (detailData.licenseUrl) {
        fileList.value = [{
          name: "营业执照.jpg",
          url: detailData.licenseUrl,
          uid: Date.now(),
          status: "success" // 标记为成功状态
        }]
      } else {
        // 如果没有图片URL，清空文件列表
        fileList.value = []
      }

      console.log("表单数据填充完成:", formData)
      console.log("文件列表状态:", fileList.value)
    } else {
      console.warn("未找到公司详情数据")
      ElMessage.warning("未找到公司详情数据")
    }
  } catch (error) {
    console.error("加载公司数据失败:", error)
    ElMessage.error("加载公司数据失败")
  } finally {
    loading.value = false
  }
}

// 重置表单
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  fileList.value = []
  Object.assign(formData, {
    companyId: 0,
    companyName: "",
    shortName: "",
    workCity: undefined,
    companyType: undefined,
    companyScale: undefined,
    contactPerson: "",
    contactPhone: "",
    contactEmail: "",
    address: "",
    introduction: "",
    licenseNo: "",
    licenseUrl: "",
    expirationTime: "",
    status: 1,
    tags: []
  })
}

// 关闭弹窗
function handleClose() {
  emit("update:modelValue", false)
  emit("close")
  // 延迟重置，避免动画期间的数据残留
  setTimeout(() => {
    resetForm()
  }, 300)
}

// 处理超出文件数量限制
function handleExceed(files: File[], uploadFiles: any[]) {
  ElMessage.warning("最多只能上传1个文件")
  // 保持列表仅1个文件
  fileList.value = uploadFiles.slice(0, 1)
}

async function customUpload(options: UploadRequestOptions) {
  const file = options.file // 文件对象（自动推断为 File 类型）
  // 根据编辑模式传递不同的businessId
  const businessId = props.editMode && props.companyId ? props.companyId : 0

  // 直接将File对象传给store的uploadLicense方法
  const response = await companyStore.uploadLicense(file, businessId)

  if (response.success) {
    const fileUrl = typeof response.data === "string"
      ? response.data
      : response.data?.url || ""

    formData.licenseUrl = fileUrl
    ElMessage.success("文件上传成功！")
    options.onSuccess(response)
  }
}

// 保存数据
async function handleSave() {
  try {
    // 表单验证
    await formRef.value.validate()

    // 提交数据
    const success = props.editMode
      ? await companyStore.updateCompany({ ...formData })
      : await companyStore.createCompany({ ...formData })

    if (success) {
      // 确保先发出success事件，让父组件刷新列表
      console.log("CompanyEditModal: 发出success事件")
      emit("success")

      // 稍作延迟再关闭模态框，确保事件处理完成
      setTimeout(() => {
        handleClose()
      }, 100)
    }
  } catch (error) {
    console.error("保存公司信息失败:", error)
  }
}
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="props.editMode ? `${companyStore.currentDetail?.companyName || '编辑公司'}` : '新增公司'"
    width="800px"
    :loading="loading || submitLoading"
    @close="handleClose"
    class="company-edit-dialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="company-edit-form"
    >
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">
          <el-icon><InfoFilled /></el-icon>
          基本信息
        </h3>

        <div class="form-row">
          <el-form-item label="公司名称" prop="companyName">
            <el-input
              v-model="formData.companyName"
              placeholder="请输入公司名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="公司简称" prop="shortName">
            <el-input
              v-model="formData.shortName"
              placeholder="请输入公司简称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="工作城市" prop="workCity">
            <el-select
              v-model="formData.workCity"
              placeholder="请选择工作城市"
              filterable
              clearable
            >
              <el-option
                v-for="option in workCityOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="公司类型" prop="companyType">
            <el-select
              v-model="formData.companyType"
              placeholder="请选择公司类型"
              filterable
              clearable
            >
              <el-option
                v-for="option in companyTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="公司规模" prop="companyScale">
            <el-select
              v-model="formData.companyScale"
              placeholder="请选择公司规模"
              filterable
              clearable
            >
              <el-option
                v-for="option in companyScaleOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="公司状态">
            <el-radio-group v-model="formData.status">
              <el-radio :label="1">
                正常
              </el-radio>
              <el-radio :label="0">
                禁用
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </div>

      <!-- 联系方式 -->
      <div class="form-section">
        <h3 class="section-title">
          <el-icon><PhoneFilled /></el-icon>
          联系方式
        </h3>

        <div class="form-row">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input
              v-model="formData.contactPerson"
              placeholder="请输入联系人"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="联系电话" prop="contactPhone">
            <el-input
              v-model="formData.contactPhone"
              placeholder="请输入联系电话"
              maxlength="11"
              show-word-limit
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="联系邮箱" prop="contactEmail">
            <el-input
              v-model="formData.contactEmail"
              placeholder="请输入联系邮箱（选填）"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="公司地址" prop="address">
            <el-input
              v-model="formData.address"
              placeholder="请输入公司地址"
              maxlength="200"
              show-word-limit
              type="textarea"
              :rows="2"
            />
          </el-form-item>
        </div>
      </div>

      <!-- 公司资质 -->
      <div class="form-section">
        <h3 class="section-title">
          <el-icon><DocumentChecked /></el-icon>
          公司资质
        </h3>

        <div class="form-row">
          <el-form-item label="营业执照号码" prop="licenseNo">
            <el-input
              v-model="formData.licenseNo"
              placeholder="请输入营业执照号码"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="营业执照到期时间" prop="expirationTime">
            <el-date-picker
              v-model="formData.expirationTime"
              type="date"
              placeholder="请选择营业执照到期时间"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </div>

        <div class="form-row">
          <el-form-item label="营业执照">
            <div class="upload-wrapper">
              <el-upload
                ref="uploadRef"
                class="upload-demo"
                action="#"
                :http-request="customUpload"
                :file-list="fileList"
                :limit="1"
                :on-exceed="handleExceed"
                :auto-upload="true"
                accept=".pdf,.jpg,.jpeg,.png"
                list-type="picture-card"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                请上传营业执照图片或PDF文件，最多上传单个文件，单个文件大小不超过10MB
              </div>
            </template>
          </el-form-item>
        </div>
      </div>

      <!-- 公司介绍 -->
      <div class="form-section">
        <h3 class="section-title">
          <el-icon><OfficeBuilding /></el-icon>
          公司介绍
        </h3>

        <div class="form-row">
          <el-form-item label="介绍内容" prop="introduction">
            <el-input
              v-model="formData.introduction"
              placeholder="请输入公司介绍（选填）"
              maxlength="500"
              show-word-limit
              type="textarea"
              :rows="4"
            />
          </el-form-item>
        </div>
      </div>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">
        取消
      </el-button>
      <el-button type="primary" @click="handleSave" :loading="submitLoading">
        {{ props.editMode ? '更新' : '创建' }}
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.upload-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

:deep(.el-upload) {
  margin-bottom: 0;
}

:deep(.el-dialog) {
  .el-dialog__header {
    background: #f8f9fa;
    padding: 20px 25px;
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .el-dialog__body {
    padding: 25px;
    max-height: calc(100vh - 200px);
    overflow-y: auto;
  }
}

.company-edit-dialog {
  .el-dialog__footer {
    padding: 15px 25px 20px;
    border-top: 1px solid #ebeef5;
  }
}

.company-edit-form {
  .form-section {
    margin-bottom: 24px;
    padding-bottom: 20px;
    border-bottom: 1px solid #f0f2f5;

    &:last-child {
      border-bottom: none;
      margin-bottom: 0;
      padding-bottom: 0;
    }
  }

  .section-title {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 16px 0;
    padding: 0 0 8px 0;
    border-bottom: 2px solid #1890ff;
  }

  .form-row {
    display: flex;
    gap: 20px;
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }

    .el-form-item {
      margin-bottom: 0;

      &:last-child {
        margin-right: 0;
      }
    }
  }
}

@media (max-width: 768px) {
  .company-edit-form {
    .form-row {
      flex-direction: column;
      gap: 16px;
    }
  }
}
</style>
